package org.example.service.pc;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.example.R.R;
import org.example.entity.dto.AddVolunteerWorkDto;
import org.example.entity.dto.UpdateVisitCountDto;
import org.example.entity.po.VolunteerWorkPO;
import org.example.entity.vo.OSSFileVO;
import org.example.entity.vo.admin.VolunteerWorkVO;
import org.example.entity.vo.pc.PCVolunteerWorkVO;
import org.example.mapper.VolunteerWorkMapper;
import org.example.service.ExService;
import org.example.utils.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class VolunteerWorkService {

    @Autowired
    private VolunteerWorkMapper volunteerWorkMapper;

    @Autowired
    private ExService exService;

    public R list() {
        List<VolunteerWorkVO> list = volunteerWorkMapper.list();
        list.sort(Comparator.comparing(VolunteerWorkVO::getVisitsCount).thenComparing(VolunteerWorkVO::getCreateDate).reversed());
        return R.success("查询成功!").setData(list);
    }

    public R detail(Long id) {
        VolunteerWorkVO volunteerWorkVO = volunteerWorkMapper.detail(id);
        if (volunteerWorkVO==null){
            return R.error("该志愿服务作品不存在!");
        }
        UpdateVisitCountDto updateVisitCountDto = new UpdateVisitCountDto();
        BeanUtils.copyProperties(volunteerWorkVO,updateVisitCountDto);
        updateVisitCountDto.setVisitsCount(volunteerWorkVO.getVisitsCount()+1);
        volunteerWorkMapper.addCount(updateVisitCountDto);
        return R.success("获取成功!").setData(volunteerWorkVO);
    }

    public R delete(Long id) {
        volunteerWorkMapper.delete(id);
        return R.success("删除成功!");
    }

    public R pcList() {
        List<VolunteerWorkVO> list = volunteerWorkMapper.list();
        List<PCVolunteerWorkVO> resultList = new ArrayList<>();
        list.forEach(obj->{
            PCVolunteerWorkVO vo = new PCVolunteerWorkVO();
            BeanUtils.copyProperties(obj,vo);
            resultList.add(vo);
        });
        resultList.sort(Comparator.comparing(PCVolunteerWorkVO::getVisitsCount).thenComparing(PCVolunteerWorkVO::getCreateDate).reversed());
        return R.success("获取成功!").setData(resultList);
    }

   public R add(AddVolunteerWorkDto dto) {
       VolunteerWorkPO po = new VolunteerWorkPO();
       BeanUtils.copyProperties(dto,po);
       OSSFileVO detail = exService.detail(po.getResourceId());
       po.setType(detail.getOssFileType());
       po.setId(IdUtil.getSnowflakeNextId());
       po.setCreateDate(TimeUtils.getCurrentDate());
       po.setDelFlag(0);
       po.setVisitsCount(0);
       volunteerWorkMapper.insert(po);
        return R.success("添加成功!");
    }
}
